import { config } from "../config.js";

class HTTP {
  request({url,data={},method="GET"}){
     return new Promise((resolve,reject)=>{
        this._request(url,resolve,reject,data,method);
      })
  }
  _request(url,resolve,reject,data={},method="GET") {
    wx.request({
      url: config.api_base_url+url,
      data: data,
      method:method,
      header: {
        'content-type': 'application/json',
        'appkey': config.appkey
      },
      success: (res) => {
        //startsWith
        //endsWith
        let cods = res.statusCode.toString(); //转为字符串
        if (cods.startsWith("2"))  //如果为2开头证明成功了
        {
          resolve(res.data);
        } else {      //服务器异常 执行*** 
        reject(); //更改promise状态
          wx.showToast({
            title: '服务器错误',
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: (res) => {   //api调用失败
        reject(); //更改promise状态
      }
    })
  }
}
export { HTTP };